<?php
namespace Particle;
use Particle\Core;

ob_start();
ob_implicit_flush(0);

error_reporting(E_ALL | E_STRICT);  // Add strict
ini_set('display_errors', '1');     // mostrar errores

define('DS', DIRECTORY_SEPARATOR);
define('ROOT', realpath(dirname(__FILE__)) . DS);
define('FRAMEWORK_FOLDER', 'Particle');
define('PARTICLE_PATH', ROOT . FRAMEWORK_FOLDER . DS);
define('APPS_FOLDER', 'Apps');
define('APPS_CONST_PATH', ROOT . APPS_FOLDER . DS . 'constants' . DS);
define('APPS_CONST_REL', APPS_FOLDER . '/' . 'constants' . '/');
define('SETTINGS_PATH', APPS_CONST_PATH .'settings.xml');


require_once PARTICLE_PATH . 'Config.php';
require_once PARTICLE_PATH . 'Security.php';
require_once APPS_CONST_PATH . 'settings.inc.php'; // TODO: Test!

Apps\Settings::getInstance()->initSettings(); // init Settings

$aFilesSettingsPHP = Apps\Settings::getInstance()->getSettingsFilephp();

//echo '<pre>';
//print_r($aFilesSettingsPHP);
//echo '</pre>';

$countFilesSettingsPHP = count($aFilesSettingsPHP);

for($in = 0; $in < $countFilesSettingsPHP; $in++){
    
    if(is_file($aFilesSettingsPHP[$in])){
        require_once $aFilesSettingsPHP[$in];
    }
    
}

require_once PARTICLE_PATH . 'Debug.php';
require_once LIBS_PATH . 'essential.php'; // TODO: Buscar lugar de include
require_once PARTICLE_PATH . 'App.php';
require_once PARTICLE_PATH . 'Request.php';
require_once PARTICLE_PATH . 'Bootstrap.php';
require_once PARTICLE_PATH . 'Controller.php';
require_once PARTICLE_PATH . 'Model.php';
require_once PARTICLE_PATH . 'View.php';
require_once PARTICLE_PATH . 'Database.php';
require_once PARTICLE_PATH . 'Session.php';
require_once PARTICLE_PATH . 'Addons.php';
require_once PARTICLE_PATH . 'ViewAddons.php';

try{
    // Session init //
    Core\Session::init();
        
    if(OUTPUT_CONTROL){
        // Get Unexpected output //
        $unexpected_output = ob_get_contents();
        
        ob_clean();
        
        // Check Unexpected output //
        if($unexpected_output){
            Core\Debug::savelogfile(1, 'Unexpected output', $unexpected_output);
            throw new \Exception('Unexpected output');
        }
    }
        
    // Run Core //
    Core\Bootstrap::run(new Core\Request);
    
    // Output //
    ob_end_flush();
    
    exit();
}
catch(\Exception $e){
    
    try{
        echo 'Error in application! ';
        Core\Debug::savelogfile(0, $e->getFile().$e->getLine(), $e->getMessage());
    } catch (\Exception $e){
        echo 'Fatal error, no error log generated! ',$e->getMessage();
    }
    
    exit();
}